package org.adw.launcher2.ld.secret.db;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.adw.launcher2.ld.secret.dom.MyPhoto;
import org.adw.launcher2.ld.secret.ui.utils.Global;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.util.Log;

public class MyPhotoCache {
	private static String TABLE_MY_PHOTO = "my_photo";
	private static MyPhotoCache instance = null;
	private SQLiteDatabase db;
	public static MyPhotoCache getInstance(DatabaseHelper dbHelper) {
		if (instance == null) {
			instance = new MyPhotoCache(dbHelper);
			
		}
		return instance;
	}

	private MyPhotoCache(DatabaseHelper dbHelper) {
		db = dbHelper.db;
		onCreateTable();
	}

	private void onCreateTable() {
		db.execSQL("CREATE TABLE IF NOT EXISTS my_photo(id  INTEGER PRIMARY KEY NOT NULL  UNIQUE, image BLOB, "
						+ "absolute_path_no_extend TEXT,extend TEXT );");
	}

	public void insertPhotoToDb(ContentValues values) {
		db.insert(TABLE_MY_PHOTO, null, values);

	}

	public void insertPhotoToMemory(MyPhoto myPhoto) {
		// luc nay trong memory (external) chua file myphoto.abc
		// bay gio ta se rename lai
		String photoLocationInMemory = myPhoto.getAbsolutePathNoExtend()
				+ ".abc";
		String photoLocation = myPhoto.getAbsolutePathNoExtend()
				+ myPhoto.getFileExtend();// trong db chua extends cu cua file
		File fileLocationInMemory = new File(photoLocationInMemory);
		File fileLocation = new File(photoLocation);
		boolean isSuccess = fileLocationInMemory.renameTo(fileLocation);
		Log.d("insertPhotoToMemory",isSuccess+"");
	}

	public void deletePhotoFromDb(long id) {
		db.delete(TABLE_MY_PHOTO, " id = ? ", new String[] { id + "" });
	}

	public void deletePhotoFromMemory(long id, Bitmap image, String absolutePath, String fileExtend) {
		File fileLocationInMemory = new File(absolutePath + fileExtend);
		Log.d("fileLocationInMemory", fileLocationInMemory.getAbsolutePath());
		File fileLocationInDb = new File(absolutePath+ ".abc");
		Log.d("fileLocationInDb", fileLocationInDb.getAbsolutePath());
		boolean isMoveSuccess = fileLocationInMemory.renameTo(fileLocationInDb);
		Log.d("MyPhotoCache:isMoveSuccess", isMoveSuccess + "");
		int rowDeleted = Global.cr.delete(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "_id = ? ",
				new String[] { id + "" });
		int row1Deleted = Global.cr.delete(
				MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "_id = ? ",
				new String[] { id+ "" });
		Log.d("deletePhotoFromMemory", rowDeleted + " " + row1Deleted);
	}

	public List<MyPhoto> getPhotosNoImageFromMemory(ContentResolver cr) {
		List<MyPhoto> listPhoto = new LinkedList<MyPhoto>();
		String[] proj = { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATA };
		Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				proj, null, null, null);

		while (cursor.moveToNext()) {
			int id = cursor.getInt(cursor
					.getColumnIndex(MediaStore.Images.Media._ID));
			String filename = cursor.getString(cursor
					.getColumnIndex(MediaStore.Images.Media.DATA));
			Log.d("filename", filename);
			String[] filterFileName = filename.split("/");
			String absolute_path_no_extend = filename.substring(0, filename
					.length() - 4);
			Log.d("absolute_path", absolute_path_no_extend);
			String fileNameWithExtention = filterFileName[filterFileName.length - 1];
			String fileExtend = fileNameWithExtention.substring(
					fileNameWithExtention.length() - 4, fileNameWithExtention
							.length());
			MyPhoto myPhoto = new MyPhoto(id, null, absolute_path_no_extend,
					fileExtend);
			listPhoto.add(myPhoto);
		}
		cursor.close();
		return listPhoto;
	}

	public Bitmap getImageOfPhotosFromMemory(ContentResolver cr, String userId){
		Bitmap image = null;
		String[] proj = { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATA };
		Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				proj, null, null, null);
		if(cursor.moveToFirst()){
			image = null;
			image = MediaStore.Images.Thumbnails.getThumbnail(cr,Long.parseLong(userId),MediaStore.Images.Thumbnails.MICRO_KIND, null);
		
		}
		cursor.close();
		return image;
	}
	public List<MyPhoto> getPhotosNoImageFromDb() {
		
		List<MyPhoto> listPhoto = new LinkedList<MyPhoto>();
		Cursor cursor = db.rawQuery("SELECT * FROM my_photo ", null);
		while (cursor.moveToNext()) {
			long id = cursor.getLong(cursor.getColumnIndex("id"));
			String absolutePathNoExtend = cursor.getString(cursor
					.getColumnIndex("absolute_path_no_extend"));
			String extend = cursor.getString(cursor.getColumnIndex("extend"));
			listPhoto.add(new MyPhoto(id, null, absolutePathNoExtend, extend));
		}
		cursor.close();
		return listPhoto;
	}
	public Bitmap getImageOfPhotosFromDb(String userId) {
		Bitmap image = null ;
		Cursor cursor = db.rawQuery("SELECT * FROM my_photo WHERE id = " + Long.parseLong(userId), null);
		
		if (cursor.moveToFirst()) {
			
			image = null;
			byte[] bb = null;
			bb = cursor.getBlob(cursor.getColumnIndex("image"));
			if(bb!=null){
					image = BitmapFactory.decodeByteArray(bb, 0, bb.length);
			}
			
		}
		cursor.close();
		return image;
	}
}
